<template>
  <base-container>
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />

    <base-table-card>
      <template #header-left>
        <el-tabs v-model="staticTabName">
          <el-tab-pane :label="tabLabel" name="notice" />
        </el-tabs>
      </template>

      <avue-crud
        ref="crudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <!-- 操作列：严格按（status/showStatus）控制 -->
        <template #menu="{ row }">
          <ActionBar :row="row" :max-inline="2" :actions="buildRowActions" />
        </template>
      </avue-crud>
    </base-table-card>
  </base-container>
</template>

<script setup>
  import Option from "@/crudOption/message/noticeList";
  import { router } from "@/router/index";
  import { ElMessageBox } from "element-plus";
  import ActionBar from "@/components/ActionBar/ActionBar.vue"; // 你的 ActionBar 组件路径
  import { createBuildNotificationActions } from "@/crudOption/message/notificationList"; // 上条给你的 actions.js

  /* --- 固定 Tabs 外观 --- */
  const staticTabName = ref("notice");
  const tabLabel = computed(() => `运维通知(${Number(page?.value.total ?? 0)})`);

  // function openAddDialog() {
  //   router.push({ name: "AddNotifications" });
  // }
  function openEditDialog(row) {
    router.push({ name: "AddNotifications", query: { id: row.id } });
  }

  /* --- CRUD --- */
  let {
    data: tableData,
    loading: tableLoading,
    page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.message.GetmsgList,
    del: Api.message.DelMsg,
    search: { categoryType: "NOTICE" },
    dataRes: "data.records", // 数据列表路径
    dataTotal: "data.total", // 数据总数路径
    getParamsFormat: params => {
      const p = { ...params };
      const split = (arr, [s, e]) => {
        if (Array.isArray(arr) && arr.length === 2) {
          p[s] = arr[0];
          p[e] = arr[1];
        }
      };
      split(p.createTime, ["saveBeginDate", "saveEndDate"]);
      delete p.createTime;
      split(p.sendTime, ["sendBeginDate", "sendEndDate"]);
      delete p.sendTime;
      split(p.updateTime, ["updateBeginDate", "updateEndDate"]);
      delete p.updateTime;
      return p;
    },
  });

  const { searchOption, tableOption } = Option(formData);

  /* ---------------- 状态判定（与后端定义一致） ---------------- */

  // 2) 注入回调 + hasAuth，得到 (row)=>actions 的闭包
  const buildRowActions = createBuildNotificationActions({
    fns: {
      openEditDialog,
      confirmHide,
      confirmShow,
      confirmResend,
      confirmSend,
      loadDel, // 直接复用你 useCrudHook 里的删除
    },
    denyStrategy: "hide", // 未授权按钮隐藏；想置灰就用 'disable'
  });
  /* ---------------- 行为（二次确认 + 刷新） ---------------- */
  async function confirmSend(row) {
    await ElMessageBox.confirm("确定发送该通知吗？", "发送确认", { type: "warning" });
    await Api.message.SendMsg?.({ id: row.id });
    $msg?.success?.("发送成功");
    loadGetTableData();
  }

  async function confirmResend(row) {
    await ElMessageBox.confirm("该通知发送失败，确定要重发吗？", "重发确认", { type: "warning" });
    await Api.message.SendMsg?.({ id: row.id });
    $msg?.success?.("重发成功");
    loadGetTableData();
  }

  async function confirmHide(row) {
    await ElMessageBox.confirm("隐藏后前台将不再展示，确认隐藏？", "隐藏确认", { type: "warning" });
    await Api.message.ShowOrHideMsg?.({ id: row.id, status: "HIDE" });
    $msg?.success?.("已隐藏");
    loadGetTableData();
  }

  async function confirmShow(row) {
    await ElMessageBox.confirm("确认在前台展示该通知？", "展示确认", { type: "info" });
    await Api.message.ShowOrHideMsg?.({ id: row.id, status: "SHOW" });
    $msg?.success?.("已展示");
    loadGetTableData();
  }

  /* --- mount --- */
  onMounted(() => {
    loadGetTableData();
  });
</script>

<style lang="scss" scoped></style>
